<template>
    <configCompositionTwoWindowStyle>
        <template slot="card">
            <search
                    @add="addCallAudio"
                    @refresh="refreshList"
                    @search="searchByName"
                    :currentPage="currentPage"
                    :count="tableData.length || 0"
                    :pageSize="tableData.length || 1"
                    :forCall="true"
                    :isReloadIvr="false"
                    :showAdvSearch="false"
                    :isShowInput="false"
                    >
            </search>
            <div style="border-top:1px solid #d9d9d9;">
                <el-row :gutter="20" style="padding:6px 10px;margin:0;">
                    <el-col :span="12">
                        <el-select size="mini" v-model="PBX" :placeholder="$t('public.pleasePick')" style="width:100%;" @change="changePBX">
                            <el-option
                                    :label="$t('public.all')"
                                    :value="''">
                            </el-option>
                            <el-option
                                    v-for="(item,index) in pbxs"
                                    :label="item.NickName + ' (' +item.PBX + ')'"
                                    :value="item.PBX"
                                    :key="index">
                            </el-option>
                        </el-select>
                    </el-col>
                    <el-col :span="12">
                        <el-input
                                :placeholder="$t('config.channel.enterVoiceFiled')"
                                class="condition"
                                v-model="searchContent"
                                size="mini"
                                @keyup.enter.native="searchByName"
                                >
                          <i
                            class="el-input__icon el-icon-search"
                            slot="suffix"
                            @click="searchByName">
                          </i>
                        </el-input>
                    </el-col>
                </el-row>
            </div>
            <call-audio-table :tableHeader="tableHeader" :tableData="tableData" @resh="commitAndQueryList" @editVoice="editVoice"></call-audio-table>
        </template>
        <template slot="detail">
            <breadCrumb v-show="isShowDetail" :titleArr="titleArr" @back="cancle"></breadCrumb>
            <call-audio-detail v-show='isShowDetail' :currentData="currentData" :isRestFrom="isRestFrom" :showBread="showBread" @resh='commitAndQueryList'  @cancle="cancle" :reshAdd="addCallAudio"></call-audio-detail>
        </template>
    </configCompositionTwoWindowStyle>
</template>
<script>
    import configCompositionTwoWindowStyle from '@/components/ui-modules/config/configCompositionTwoWindowStyle'
    import search from '../base/search'
    import CallAudioTable from './CallAudioTable.vue'
    import CallAudioDetail from './CallAudioDetail.vue'
    import {ivrSearch, deepClone} from '@/utils/m7Utils.js'
    import breadCrumb from '@/components/ui-modules/breadCrumb/BreadCrumbConfig.vue'
    export default {
      name: 'callAudioLibrary',
      data () {
        return {
          currentPage: 1,    //   当前页
          tableHeader: [
            {prop: 'DisplayName', label: this.$t('config.channel.voiceFiledName')},
            {prop: 'Memo', label: this.$t('config.channel.voiceFiledExplain')},
            {prop: 'UpdateTime', label: this.$t('config.channel.lastUpdateTime')},
            {prop: 'PBX', label: 'PBX'},
            {prop: '', label: this.$t('sms.operate')}
          ],                        //   自定义 表头
          isShowDetail: false, //   是否要展示右边
          tableData: [],
          showBread: 'addVoice',
          currentData: {},
          emptyFrom: {Account: this.$store.state.session.account.account, DisplayName: '', Filename: '', Memo: '', PBX: this.$store.state.session.user.pbx, SoundType: 'normal', UpdateTime: '', UpdateUser: '', fileUrl: '', _id: ''},
          pbxs: [],
          PBX: '',
          searchContent: '',
          ivrSoundList: [],
          isRestFrom: 0,
          titleArr: [this.$t('config.channel.voiceLibrary'), this.$t('config.channel.addVoice')],
          currentPbxList: [], // 当前的pbx的数据
          currentPBX: this.$store.state.session.user.pbx
        }
      },
      components: {
        configCompositionTwoWindowStyle,
        search,
        CallAudioTable,
        CallAudioDetail,
        breadCrumb
      },
      methods: {
        changePBX (pbx) {
          this.isShowDetail = false
          this.queryList('', pbx, 'searchPbx')
        },
        searchByName () { // 根据名字本地搜索
          this.isShowDetail = false
          let searchResult = ivrSearch(this.ivrSoundList, this.searchContent, ['DisplayName']) || []
          this.tableData = searchResult
        },
        cancle () {
          this.isShowDetail = false
        },
        commitAndQueryList (pbx) {
          this.currentPBX = pbx
          this.searchContent = ''
          this.PBX = ''
          this.queryList('commit')
        },
        refreshList () {
          this.searchContent = ''
          this.PBX = ''
          this.queryList()
        },
        queryList (commitFlag, pbx, searchPbx) { // 获取列表或者是刷新列表
          let data = {}
          data.Account = this.$store.state.session.account.account
          if (pbx) {
            data.PBX = pbx
          }
          this.$store.dispatch('querySound', data).then(resp => {
            if (resp && resp.success) {
              this.isShowDetail = false
              this.ivrSoundList = resp.list
              this.getNewAudioData(resp.list, pbx, searchPbx)
              if (commitFlag) {
                this.$store.commit('SET_IVRMAP_DETAIL', {PBX: this.currentPBX, typeName: 'ivr_sound', data: this.currentPbxList || [], flag: 'data', node: this})
                this.currentPBX = this.$store.state.session.user.pbx
                console.log(this.currentPbxList)
              }
            } else {
              this.$message.error(this.$t('查询失败！'))
            }
          })
        },
        getNewAudioData (data, pbx, searchPbx) {
          let newArr = []
          this.currentPbxList = []
          for (let i = 0; i < data.length; i++) {
            if (data[i].PBX === this.currentPBX) {
              this.currentPbxList.push(data[i])
            }
            let soundFileName = ''
            let fileUrl = ''
            if (!data[i].Memo || data[i].Memo === ' ') {
              data[i].Memo = '--'
              data[i].MemoFlag = true
            }
            if (data[i].IsQiniuMusic && data[i].IsQiniuMusic === 'yes') {
              soundFileName = data[i].Filename.substring(0, data[i].Filename.indexOf('.'))
              fileUrl = data[i].QiniuMusicUrl.replace('@', '=/')
              let tmpTag = false
              if (document.location.protocol === 'https:') {
                tmpTag = true
              }
              if (tmpTag) {
                fileUrl = fileUrl.replace('http', 'https')
              }
            } else {
              soundFileName = data[i].Filename.substring(0, data[i].Filename.indexOf('.'))
              let loginToken = window.sessionStorage.getItem('loginToken')
              fileUrl = './' + 'fileDownload/?sessionId=' + this.$store.state.session.sessionId + '&fileId=' + soundFileName + '&loginToken=' + loginToken
            }
            data[i].fileUrl = fileUrl
            if (searchPbx === 'searchPbx') { // 更改pbx时
              if (pbx) {
                if (data[i].PBX === pbx) {
                  newArr.push(data[i])
                }
              } else { // 全选时
                newArr.push(data[i])
              }
            }
          }
          if (searchPbx === 'searchPbx') { // 先根据pbx筛选，然后根据名字再筛选
            let searchResult = ivrSearch(newArr, this.searchContent, ['DisplayName']) || []
            this.tableData = searchResult
          } else {
            this.tableData = data
          }
        },
        addCallAudio () { // 添加录音
          this.isShowDetail = true
          this.showBread = 'addVoice'
          this.titleArr.splice(1, 1, this.$t('config.channel.addVoice'))
          this.currentData = deepClone(this.emptyFrom)
          this.isRestFrom = Math.random()
        },
        editVoice (val) { // 修改录音
          if (val.Memo === '--' && val.MemoFlag) {
            val.Memo = ''
          }
          this.currentData = deepClone(val)
          this.isShowDetail = true
          this.showBread = 'editVoice'
          this.titleArr.splice(1, 1, this.$t('config.channel.editVoice'))
          this.isRestFrom = Math.random()
        }
      },
      beforeMount () {
        this.queryList()
        this.pbxs = this.$store.state.session.account.pbx
      }
    }
</script>
<style lang="stylus" scoped>
    @import "../../../../../assets/common.styl"
</style>
